package com.standard.logcat

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.WindowManager
import com.standard.logcat.databinding.LogcatWindowLayoutBinding

@SuppressLint("InflateParams")
abstract class FloatingWindow(private val context: Context) {

    protected val binding: LogcatWindowLayoutBinding

    protected val screenWidth: Int
    protected val screenHeight: Int

    //获取manager
    private val windowManager: WindowManager =
        context.getSystemService(Context.WINDOW_SERVICE) as WindowManager

    //悬浮窗参数
    private val layoutParams = WindowManager.LayoutParams()

    //初始化悬浮窗参数
    init {
        screenWidth = windowManager.defaultDisplay.width
        screenHeight = windowManager.defaultDisplay.height

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O) {
            layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY
        } else {
            layoutParams.type = WindowManager.LayoutParams.TYPE_PHONE
        }

        //悬浮窗弹出的位置
        layoutParams.gravity = Gravity.END or Gravity.TOP

        //不让悬浮窗占据屏幕的焦点
        layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE

        layoutParams.format = PixelFormat.RGBA_8888

        layoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT

        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT

        layoutParams.x = 0

        layoutParams.y = 0

        binding = LogcatWindowLayoutBinding.inflate(LayoutInflater.from(context))
        windowManager.addView(binding.root, layoutParams)
        initAll()
    }

    private fun initAll() {
        initListener()
        initView()
    }

    abstract fun initListener()
    abstract fun initView()

}